
/**
 * Please modify this class to meet your needs
 * This class is not complete
 */

package com.cctv.eip.eipmessageservice._0_1;

import com.cctv.eip.schema.eip_commoncomplextype._0.MessageState;
import com.cctv.eip.schema.eip_commoncomplextype._0.MessageStates;
import com.cctv.eip.schema.eip_commoncomplextype._0.PubMessageResp;
import com.cctv.eip.schema.eip_commoncomplextype._0.SubMessageResp;
import com.cctv.eip.schema.eip_commondatatypes._0.BatchPubResponseType;
import com.cctv.eip.schema.eip_commondatatypes._0.QueryPubResponseType;
import com.cctv.eip.schema.eip_commonsimpletype._0.OperateTypeType;
import com.ctvit.common.Constants;
import com.ctvit.framework.web.context.ContextHolder;
import com.ctvit.sms.platform.service.MsgService;
import com.ctvit.wsservice.basedata.domain.EipMessageBatchPub;
import com.ctvit.wsservice.basedata.domain.EipMessageMember;
import com.ctvit.wsservice.basedata.domain.EipMessageQueryPub;
import com.ctvit.wsservice.basedata.domain.EipMessageQuerySub;
import com.ctvit.wsservice.basedata.service.EIPMessageProcessService;
import org.apache.commons.lang.StringUtils;
import org.apache.log4j.Logger;

import java.sql.Timestamp;
import java.util.ArrayList;
import java.util.GregorianCalendar;
import java.util.List;
import java.util.UUID;
import javax.jws.WebService;

/**
 * This class was generated by Apache CXF 3.1.6
 * 2016-04-26T09:50:24.332+08:00
 * Generated source version: 3.1.6
 */

@WebService(
		serviceName = "EIPMessageService",
		portName = "EIPMessagePortType",
		targetNamespace = "http://cctv.com/EIP/EIPMessageService/0.1",

		endpointInterface = "com.cctv.eip.eipmessageservice._0_1.EIPMessagePortType")

public class EIPMessagePortTypeImpl implements EIPMessagePortType {
	private static final Logger LOG = Logger.getLogger(EIPMessagePortTypeImpl.class);

	/* (non-Javadoc)
	 * @see com.cctv.eip.eipmessageservice._0_1.EIPMessagePortType#getServiceInfo(com.cctv.esb.schema.monitor._0.GetServiceInfoRequestType  getServiceInfoRequest )*
	 */
	public com.cctv.esb.schema.monitor._0.GetServiceInfoResponseType getServiceInfo(com.cctv.esb.schema.monitor._0.GetServiceInfoRequestType getServiceInfoRequest) {
		LOG.info("Executing operation getServiceInfo");
		System.out.println(getServiceInfoRequest);
		try {
			com.cctv.esb.schema.monitor._0.GetServiceInfoResponseType _return = null;
			return _return;
		} catch (Exception ex) {
			ex.printStackTrace();
			throw new RuntimeException(ex);
		}
	}


	/**
	 * 应用系统可以调用该方法查询应用系统的上行信息，需填入应用系统的系统编码与安全码和开始时间，返回值为一个QueryPubResponseType。
	 * 由于需要给供应商一个回调函数的地址 因为网络问题  所以暂时未开通
	 *
	 * @param requestHead
	 * @param querySubRequest
	 * @return returnStatus  = 1 失败
	 * @see com.cctv.eip.eipmessageservice._0_1.EIPMessagePortType#querySubMessage(com.cctv.esb.schema.messagehead._0.RequestHeadType  requestHead,)com.cctv.eip.schema.eip_commondatatypes._0.QuerySubRequestType  querySubRequest )*
	 */
	public com.cctv.eip.schema.eip_commondatatypes._0.QuerySubResponseType querySubMessage(com.cctv.esb.schema.messagehead._0.RequestHeadType requestHead,
	                                                                                       com.cctv.eip.schema.eip_commondatatypes._0.QuerySubRequestType querySubRequest) {
		LOG.info("Executing operation querySubMessage");
		EIPMessageProcessService processService = ContextHolder.getBean(EIPMessageProcessService.class);
		com.cctv.eip.schema.eip_commondatatypes._0.QuerySubResponseType _return = new com.cctv.eip.schema.eip_commondatatypes._0.QuerySubResponseType();
		SubMessageResp subMessageResp = new SubMessageResp();
		subMessageResp.setStateType("1");  //默认验证失败

		try {
			//先将请求存在数据库中
			EipMessageQuerySub querySub = new EipMessageQuerySub();
			//head
			querySub.setHeadSourceSysid(requestHead.getSourceSysID());
			querySub.setHeadTargetSysid(requestHead.getTargetSysID());
			querySub.setHeadTargetService(requestHead.getTargetService());
			querySub.setHeadRequestid(requestHead.getRequestID());
			//body
			querySub.setBodyMemberCodeType(querySubRequest.getMemberCodeType());
			querySub.setBodyMemberSecureType(querySubRequest.getMemberSecureType());
			querySub.setFromTimeType(querySubRequest.getFromTimeType().toString());       //开始时间
			//基础信息
			querySub.setCreateTimestamp(new Timestamp(GregorianCalendar.getInstance().getTimeInMillis()));
			//设置返回值
			querySub.setReturnStatus("1");       //TODO 先设置为失败  因为需要给供应商一个回调函数的地址 再因为网络问题 所以暂时未开通

			//插入
			processService.insertEIPMessageQuerySub(querySub);
			//设置返回Resp
			subMessageResp.setStateType(querySub.getReturnStatus());
			_return.setSubMessageResp(subMessageResp);
			return _return;
		} catch (Exception ex) {
			ex.printStackTrace();
//			throw new RuntimeException(ex);
		}
		return _return;
	}


	/**
	 * 应用系统可以调用该方法查询短信的发送状态，需填入应用系统的系统编码与安全码和短信的批次号，
	 * 返回值为一个QueryPubResponseType。
	 *
	 * @param requestHead
	 * @param queryPubRequest
	 * @return returnStatus  = 1 失败
	 * @see com.cctv.eip.eipmessageservice._0_1.EIPMessagePortType#queryPubMessage(com.cctv.esb.schema.messagehead._0.RequestHeadType  requestHead,)com.cctv.eip.schema.eip_commondatatypes._0.QueryPubRequestType  queryPubRequest )*
	 */
	public com.cctv.eip.schema.eip_commondatatypes._0.QueryPubResponseType queryPubMessage(com.cctv.esb.schema.messagehead._0.RequestHeadType requestHead,
	                                                                                       com.cctv.eip.schema.eip_commondatatypes._0.QueryPubRequestType queryPubRequest) {
		LOG.info("Executing operation queryPubMessage");
		EIPMessageProcessService processService = ContextHolder.getBean(EIPMessageProcessService.class);
		QueryPubResponseType _return = new QueryPubResponseType();    //  1
		PubMessageResp pubMessageResp = new PubMessageResp();         //  1.1
		String returnStatus;                                                                           //  1.1.1
		MessageStates messageStates = new MessageStates();                    //  1.1.1.2
		List<MessageState> messageState = messageStates.getMessageState();       //1.1.1.2.1     获取  messageStates中的  messageState

		messageState.add(new MessageState());
		try {
			//先将请求存在数据库中
			EipMessageQueryPub queryPub = new EipMessageQueryPub();
			String memberCode = queryPubRequest.getMemberCodeType().toUpperCase();
			String secureCode = queryPubRequest.getMemberSecureType().toUpperCase();
			String batchCode = queryPubRequest.getBatchCodeType();
			//head
			queryPub.setHeadSourceSysid(requestHead.getSourceSysID());
			queryPub.setHeadTargetSysid(requestHead.getTargetSysID());
			queryPub.setHeadTargetService(requestHead.getTargetService());
			queryPub.setHeadRequestid(requestHead.getRequestID());
			//body
			queryPub.setBodyMemberCodeType(queryPubRequest.getMemberCodeType());
			queryPub.setBodyMemberSecureType(queryPubRequest.getMemberSecureType());
			queryPub.setBatchCodeType(queryPubRequest.getBatchCodeType());    //调用发送接口时 返回的UUID
			//基础信息
			queryPub.setCreateTimestamp(new Timestamp(GregorianCalendar.getInstance().getTimeInMillis()));
			//不管返回值，先存包
			Long pk = processService.insertEIPMessageQueryPub(queryPub);
			queryPub.setPk(pk);

			//检查是否注册
			boolean isValid;
			isValid = validateCode(memberCode, secureCode);
			if (isValid == false) {
				returnStatus = Constants.INTERFACE_MESSAGE_ERROR;
			} else {
				returnStatus = Constants.INTERFACE_MESSAGE_OK;
				//TODO 查找uuid对应的每一条短信的状态
//				String pubStateType  = changeResultCode();
//				messageState.add(pubStateType)   ;
			}

		} catch (Exception e) {
			e.printStackTrace();
			LOG.error(e.getMessage(), e.getCause());
			returnStatus = Constants.INTERFACE_MESSAGE_ERROR;

		}

		//设置返回值
		pubMessageResp.setMessageStates(messageStates);
		pubMessageResp.setStateType(returnStatus);
		_return.setPubMessageResp(pubMessageResp);
		return _return;
	}

	/**
	 * 应用系统可以调用该方法一次向多个手机号发送相同的内容的短信，需填入应用系统的系统编码与安全码，
	 * 返回值为一个批次号。应用系统可以根据该批次号查询短信的发送状态。
	 *
	 * @param requestHead
	 * @param batchPubRequest
	 * @return status = 1   提交消息失败，系统编码参数有误
	 * status = 0   消息已接收 但是内部处理失败
	 * status =   36位字符串  消息处理批次号
	 * @see com.cctv.eip.eipmessageservice._0_1.EIPMessagePortType#batchPubMessage(com.cctv.esb.schema.messagehead._0.RequestHeadType  requestHead,)com.cctv.eip.schema.eip_commondatatypes._0.BatchPubRequestType  batchPubRequest )*
	 */
	public com.cctv.eip.schema.eip_commondatatypes._0.BatchPubResponseType batchPubMessage(com.cctv.esb.schema.messagehead._0.RequestHeadType requestHead,
	                                                                                       com.cctv.eip.schema.eip_commondatatypes._0.BatchPubRequestType batchPubRequest) {
		LOG.info("Executing operation batchPubMessage");
		BatchPubResponseType _return = new BatchPubResponseType();
		String returnStatus = "";
		try {
			// 先将请求存在数据库
			EipMessageBatchPub batchPub = new EipMessageBatchPub();
			String memberCode = batchPubRequest.getMemberCodeType().toUpperCase();
			String secureCode = batchPubRequest.getMemberSecureType().toUpperCase();
			String batchCode = UUID.randomUUID().toString().toUpperCase();
			boolean isValid;

			//head
			batchPub.setHeadSourceSysid(requestHead.getSourceSysID());
			batchPub.setHeadTargetSysid(requestHead.getTargetSysID());
			batchPub.setHeadTargetService(requestHead.getTargetService());
			batchPub.setHeadRequestid(requestHead.getRequestID());
			//body
			batchPub.setBodyMemberCodeType(memberCode);
			batchPub.setBodyMemberSecureType(secureCode);
			batchPub.setBodyDestNumbersType(batchPubRequest.getDestNumbersType());
			batchPub.setBodyContentType(batchPubRequest.getContentType());

			String operaType = batchPubRequest.getOperaType().toString();
			batchPub.setBodyOperaType(operaType);
			//基础信息
			batchPub.setProcessStatus("0");
			batchPub.setCreateTimestamp(new Timestamp(GregorianCalendar.getInstance().getTimeInMillis()));

			//检查是否注册
			isValid = validateCode(memberCode, secureCode);
			if (isValid == false) {
				returnStatus = Constants.INTERFACE_MESSAGE_ERROR;
			} else {
				returnStatus = batchCode;
			}

			//设置返回值后保存          不管是否注册 都得存
			batchPub.setReturnStatus(returnStatus);

			EIPMessageProcessService processService = ContextHolder.getBean(EIPMessageProcessService.class);
			Long pk = processService.insertEIPMessageBatchPub(batchPub);

			//看看需不需要发送
			if (isValid == true) { //验证成功就调用发送
				if (OperateTypeType.S.toString().equals(operaType)) {      //如果是紧急发送
					doSendImd(pk);
				} else {
					doSendExecProc(pk);
				}
			}
		} catch (Exception e) {
			e.printStackTrace();
			LOG.error(e.getMessage(), e.getCause());
			returnStatus = Constants.INTERFACE_MESSAGE_OK;
		}
		_return.setStatus(returnStatus);
		return _return;
	}

	/**
	 * 立即发送短消息
	 *
	 * @param pk
	 */
	private void doSendImd(Long pk) {
		LOG.debug("doSendImd");
		MsgService msgService = ContextHolder.getBean(MsgService.class);
		msgService.doExecProc("p_generate_msgreq", "t_eip_message_batch_pub", pk.toString());
	}

	/**
	 * 通过后台轮询 发送短信
	 *
	 * @param pk
	 */
	private void doSendExecProc(Long pk) {
		LOG.debug("doSendExecProc");
		EIPMessageProcessService processService = ContextHolder.getBean(EIPMessageProcessService.class);
		processService.doGeneSMS(pk);
	}

	/**
	 * 检查系统是否注册
	 *
	 * @param memberCode
	 * @param secureCode
	 * @return
	 */
	private boolean validateCode(String memberCode, String secureCode) {
		EIPMessageProcessService processService = ContextHolder.getBean(EIPMessageProcessService.class);

		EipMessageMember member = processService.findByMemberCode(memberCode);
		if (member != null && StringUtils.equalsIgnoreCase(member.getSecureCode(), secureCode)
				&& Constants.VALID_APP_TYPE.intValue() == member.getStatus().intValue()) {
			return true;
		}
		return false;
	}

	/**
	 * 针对企信通网关转换短信状态码
	 *
	 * @param resultCode
	 * @return
	 */
	public static String changeResultCode(String resultCode) {
		String result = Constants.WS_SEND_ERROR;
		if (StringUtils.equals(resultCode, Constants.QTX_ONE_SUCCESS)
				|| StringUtils.equals(resultCode, Constants.QTX_BATCH_SUCCESS)) {

			return Constants.WS_SENDED_UNREPORT;
		} else if (StringUtils.equals(resultCode, Constants.QTX_BALANCE_ERROR)
				|| StringUtils.equals(resultCode, Constants.QTX_SYS_ERROR)
				|| StringUtils.equals(resultCode, Constants.QTX_IP_VALID)) {

			return Constants.WS_SEND_ERROR;
		} else if (StringUtils.equals(resultCode, Constants.QTX_CONTENT_ERROR)
				|| StringUtils.equals(resultCode, Constants.QTX_CONFIG_ERROR)) {

			return Constants.WS_ERROR_PARAM;

		} else if (StringUtils.equals(resultCode, Constants.QTX_EXTCODE_ERROR)
				|| StringUtils.equals(resultCode, Constants.QTX_USER_ERROR)
				|| StringUtils.equals(resultCode, Constants.QTX_PASSWD_ERROR)
				|| StringUtils.equals(resultCode, Constants.QTX_SENDTIME_ERROR)
				|| StringUtils.equals(resultCode, Constants.QTX_USER_LIMIT)) {

			return Constants.WS_UNSEND_ERROR;
		}     //TODO 如果不是Constants的错误(原谷明中catch系统异常
		// state存的Constants.QTX_SYS_ERROR  但是现在没存Constants.QTX_SYS_ERROR 存的是e.ptring())
		return result;
	}
}
